package myJs.common

import myJs.Implicits._
import myJs.MyPages
import myJs.api.Api
import myJs.cps.BootstrapTableCp.Column
import myJs.cps.project.QrcodeModalCp
import myJs.cps.{BootstrapTableCp, Style}
import myJs.myPkg._
import myJs.myPkg.highcharts._
import myJs.myPkg.reactHookForm.{ReactHookForm, UseFormOptions}
import myJs.tool.Pojo._
import myJs.tool.Tool
import org.scalajs.dom.html
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Sample._
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.{Fragment, React}
import slinky.web.html._

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import scala.scalajs.js.JSON
import typings.csstype.csstypeStrings

/**
 * Created by yz on 21/1/2022
 */
@react object SampleIdManageCp {

  case class Props(
                    viewSamplePage: MyPages
                  )

  val component = FunctionalComponent[Props] { props =>
    val (datas, setDatas) = useState(List.empty[ujson.Obj])
    val (qrcodeId, setQrcodeId) = useState("")
    val (qrcodeShow, setQrcodeShow) = useState(false)
    val (qrcodesShow, setQrcodesShow) = useState(false)
    val (selectedIds, setSelectedIds) = useState(List[String]())
    val (addShow, setAddShow) = useState(false)

    object FTool {

      def batchShow = () => {
        setQrcodesShow(true)
      }

      def showQrcode(idStr: String) = () => {
        setQrcodeId(idStr)
        setQrcodeShow(true)
      }

      def addShowChange = (v: Boolean) => {
        setAddShow(v)
      }

      def selectedIdsChange = (v: List[String]) => {
        setSelectedIds(v)
      }

      def refreshTableB = () => {
        Api.sampleId.all.map { response =>
          setDatas(response)
        }
      }

      def qrcodeShowChange = (v: Boolean) => {
        setQrcodeShow(v)
      }

      def qrcodesShowChange = (v: Boolean) => {
        setQrcodesShow(v)
      }


      def addShow = () => {
        setAddShow(true)
      }


      def comVFmt(fileTitle: String) = (v: ujson.Value, row: ujson.Obj) => {
        fileTitle match {
          case _ => v.toString
        }
      }

      def tbFmt(field: String) = (v: ujson.Value, row: ujson.Obj) => {
        field match {
          case "id" =>
            if (row("status").str == "已使用") {
              span(
                a(href := s"${props.viewSamplePage.absolutePath}?id=${row("id").str}", s"${v.str}"),
                " ",
                i(className := "fa fa-qrcode", style := Style(cursor = csstypeStrings.pointer),
                  onClick := FTool.showQrcode(v.str))
              )()
            } else {
              span(
                span(s"${v.str}"),
                " ",
                i(className := "fa fa-qrcode", style := Style(cursor = csstypeStrings.pointer),
                  onClick := FTool.showQrcode(v.str))
              )()
            }

          case _ => span(v.myStr)()
        }
      }

      def delete(id: String) = () => {
        val options = SwalOptions(title = "", text = "确定要删除此数据吗？", `type` = "warning", showCancelButton = true,
          showConfirmButton = true, confirmButtonClass = Tool.confirmButtonClass, confirmButtonText = "确定",
          closeOnConfirm = false, cancelButtonText = "取消", showLoaderOnConfirm = true,
          cancelButtonClass = Tool.cancelButtonClass)
        swal(options, () => {
          Api.sampleId.delete(id).map { str =>
            refreshTableB().map { x =>
              swal(SwalOptions(title = "成功", text = "删除成功", `type` = "success"))
            }
          }
        })
      }

      def deletes = () => {
        val options = SwalOptions(title = "", text = "确定要将选中的数据删除吗？", `type` = "warning", showCancelButton = true,
          showConfirmButton = true, confirmButtonClass = Tool.confirmButtonClass, confirmButtonText = "确定",
          closeOnConfirm = false, cancelButtonText = "取消", showLoaderOnConfirm = true,
          cancelButtonClass = Tool.cancelButtonClass)
        swal(options, () => {
          Api.sampleId.deletes(IdStrsData(ids = selectedIds)).map { str =>
            refreshTableB().map { x =>
              swal(SwalOptions(title = "成功", text = "删除成功", `type` = "success"))
            }
          }
        })
      }

      def operateFmt = (v: ujson.Value, row: ujson.Obj) => {
        span(
          a(style := Style(cursor = csstypeStrings.pointer), className := "btn btn-danger btn-xs",
            title := "删除", onClick := FTool.delete(s"${row("id").str}"),
            target := "_blank",
            span(
              em(className := "fa fa-remove", "删除")
            )
          )
        )()
      }

    }

    useEffect(() => {
      FTool.refreshTableB()
    }, List()
    )

    val map = SeqMap("id" -> "样本编号", "status" -> "使用状态", "memberAccount" -> "创建人员", "downloadTime" -> "创建时间")
    val basicColumns = map.map { case (k, v) =>
      val searchKind = k match {
        case "id" => TextSearch
        case "downloadTime" => DateSearch
        case "status" => CheckboxSearch
        case _ => TextSearch
      }
      val fmt = FTool.tbFmt(k)
      val comVF = FTool.comVFmt(v)
      val optionMap = searchKind match {
        case CheckboxSearch => List("已使用", "未使用").optionMap
        case _ => SeqMap[String, String]()
      }
      Column(field = k, title = v, operable = true, searchKind = searchKind, formatter = fmt, comVF = comVF,
        optionMap = optionMap)
    }.toList
    val checkColumn = Column(field = "state", checkbox = true, comVF = FTool.comVFmt(""))
    val operateColumn = Column(field = "operate", title = "操作", formatter = FTool.operateFmt, comVF = FTool.comVFmt(""))
    val columns = (checkColumn :: basicColumns) :+ operateColumn
    val batchDisabled = selectedIds.isEmpty
    val deletesDisabled = selectedIds.isEmpty

    Fragment(

      div(className := "table-responsive",
        div(id := "toolbar",
          button(className := "btn btn-primary myAddShow", onClick := FTool.addShow,
            i(className := "fa fa-plus"), " 新增样本编号"
          ), " ",
          button(className := "btn btn-primary", disabled := batchDisabled,
            onClick := FTool.batchShow,
            s" 批量操作",
          ), " ",
          button(style := Style(marginBottom = 10), className := "btn btn-danger", onClick := FTool.deletes,
            disabled := deletesDisabled,
            i(className := "fa fa-trash"), " 批量删除"
          ), " ",
        ),

        BootstrapTableCp(columns = columns, datas = datas,
          pageList = List(10, 25), pageSize = 10, selectedIds = selectedIds,
          selectedIdsChange = FTool.selectedIdsChange),
      ),
      AddCp(refreshTableB = FTool.refreshTableB, show = addShow, showChange = FTool.addShowChange),
      QrcodeModalCp(show = qrcodeShow, showChange = FTool.qrcodeShowChange,
        sampleId = qrcodeId),
      QrcodesModalCp(show = qrcodesShow, showChange = FTool.qrcodesShowChange,
        sampleIds = selectedIds)


    )


  }


}
